package com.example.bookservice.exception;

import com.example.commom.exception.CustomException;
import com.example.feign.result.AjaxResult;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

@ControllerAdvice
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {
//
//    /**
//     * 运行时异常处理
//     */
//    @ExceptionHandler(RuntimeException.class)
//    public AjaxResult exceptionHandler(RuntimeException e){
//        log.error("错误原因为: " + e.getMessage());
//        return AjaxResult.fail(e.getMessage());
//    }

    /**
     *  JWT 验证错误
     */
    @ExceptionHandler(value = JwtException.class)
    public AjaxResult exceptionHandler(JwtException e){
        log.error("错误原因为: " + e.getMessage());
        return AjaxResult.fail(e.getMessage());
    }

    /**
     *  自定义的异常
     */
    @ExceptionHandler(value = CustomException.class)
    public AjaxResult CustomExceptionHandler(CustomException e){
        log.error("错误原因为："+e.getMessage());
        int code = e.getCode();
        return AjaxResult.fail(code, e.getMessage());
    }

    /**
     *  数据库异常
     */
    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public AjaxResult exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.error("错误原因为: " + e.getMessage());
        return AjaxResult.fail(e.getMessage());
    }

    /**
     *  请求参数转换异常
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public AjaxResult exceptionHandler(HttpMessageNotReadableException e){
        log.error("错误原因为: " + e.getMessage());
        return AjaxResult.fail(e.getMessage());
    }
    /**
     *  拦截校验属性不符合要求的时候的异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        String defaultMessage = fieldErrors.get(0).getDefaultMessage();
        log.error("错误原因为："+defaultMessage);
        return AjaxResult.fail(defaultMessage);
    }

}
